import axios from 'axios'
import { Router } from 'vue-router'

// 从外部导入一下router
let router: Router = null
export const setRequestRouter = (r: Router) => {
  router = r
}

// 配置项
const instance = axios.create({
  baseURL: '/RBSapi1',
  // baseURL: 'http://120.26.171.117:7033',
  timeout: 15000,
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    let token = window.localStorage.getItem('token')
    if (token) config.headers.Authorization = token
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    if (response.data.message === 'NoLogin') {
      window.localStorage.removeItem('token')
      return router.push('/login')
    }
    // 对响应数据做点什么
    return response.data
  },
  function (error) {
    if (error.response && error.response.status === 401) {
      router.push('/login')
    }

    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

export { instance }
